<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item label="spu名称" prop="spuId">
        <el-select v-model="queryParams.spuId" placeholder="请选择spu名称" clearable filterable>
          <el-option v-for="spu in productSpuList" :key="spu.id" :label="spu.name" :value="spu.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="SKU编码" label-width="90px" prop="code">
        <el-input v-model="queryParams.code" placeholder="请输入SKU编码" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="创建时间" style="width: 308px">
        <el-date-picker v-model="daterangeCreatedAt" value-format="YYYY-MM-DD" type="daterange" range-separator="-"
          start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['product:sku:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['product:sku:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['product:sku:remove']">删除</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="skuList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <template v-for="(item, index) in columns" :key="index">
        <el-table-column :label="item.label" :align="item.align" :prop="item.prop" :width="item.width"
          v-if="item.visible">
          <template #default="scope">
            <span v-if="item.prop === 'createdAt' || item.prop === 'updatedAt'">
              {{ parseTime(scope.row[item.prop], '{y}-{m}-{d}') }}
            </span>
            <div v-else-if="item.prop === 'productImages'" class="image-cell">
              <div v-if="scope.row.productImages && scope.row.productImages.length > 0">
                <el-image 
                  :src="scope.row.productImages[0].url" 
                  :preview-src-list="scope.row.productImages.map(img => img.url)"
                  :initial-index="0"
                  :preview-teleported="true"
                  :style="{ width: '50px', height: '50px' }"
                  fit="cover"
                  lazy
                  class="product-image"
                  append-to-body />
              </div>
              <span v-else class="no-image">无图片</span>
            </div>
            <el-tag v-else-if="item.prop === 'status'" :type="scope.row.status == 1 ? 'success' : 'danger'">
              {{ scope.row.status == 1 ? '启用' : '禁用' }}
            </el-tag>
            <span v-else>{{ scope.row[item.prop] }}</span>
          </template>
        </el-table-column>
      </template>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="300">
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="handleDetail(scope.row)"
            v-hasPermi="['product:sku:list']">详情</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['product:sku:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['product:sku:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />
  </div>
</template>

<script setup name="SkuList">
import { listSku, getSku, delSku } from "@/api/product/sku";
import { listProductSpu } from "@/api/product/productSpu";
import { listProductCategory } from "@/api/product/productCategory";

import { useRouter } from 'vue-router';
import { onMounted } from "vue";
import { ElImage } from 'element-plus' // 导入ElImage组件

const router = useRouter();

const { proxy } = getCurrentInstance();

const skuList = ref([]);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const productSpuList = ref([]);
// const productCategoryOptions = ref([]);
const daterangeCreatedAt = ref([]);
const daterangeUpdatedAt = ref([]);

// 列显隐数据
const columns = ref([
  { key: 1, label: `SKU编码`, prop: `code`, align: `center`, visible: true, width: `200` },
  { key: 4, label: `销售价`, prop: `price`, align: `center`, visible: true },
  { key: 5, label: `原价`, prop: `originalPrice`, align: `center`, visible: true },
  { key: 6, label: `成本价`, prop: `costPrice`, align: `center`, visible: true },
  { key: 7, label: `库存数量`, prop: `stock`, align: `center`, visible: true },
  { key: 8, label: `库存预警值`, prop: `lowStock`, align: `center`, visible: true, width: `100` },
  { key: 9, label: `重量(g)`, prop: `weight`, align: `center`, visible: true, width: `100` },
  { key: 10, label: `体积(cm³)`, prop: `volume`, align: `center`, visible: true, width: `100` },
  { key: 11, label: `商品图片`, prop: `productImages`, align: `center`, width: `200`, visible: true },
  { key: 13, label: `创建时间`, prop: `createdAt`, align: `center`, width: `180`, visible: true },
  { key: 14, label: `更新时间`, prop: `updatedAt`, align: `center`, width: `180`, visible: true },
  { key: 12, label: `状态`, prop: `status`, align: `center`, visible: true },
]);

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    spuId: null,
    categoryId: null,
    code: null,
    categoryId: null,
    status: null,
    createdAt: null,
  },
  queryAllParams: {
    pageSize: 9999
  }
});

const { queryParams, queryAllParams } = toRefs(data);

/** 查询商品SKU列表 */
function getList() {
  loading.value = true;
  queryParams.value.params = {};
  if (daterangeCreatedAt.value && daterangeCreatedAt.value.length > 0) {
    queryParams.value.params["beginCreatedAt"] = daterangeCreatedAt.value[0];
    queryParams.value.params["endCreatedAt"] = formatEndDate(daterangeCreatedAt.value[1]);
  }
  if (daterangeUpdatedAt.value && daterangeUpdatedAt.value.length > 0) {
    queryParams.value.params["beginUpdatedAt"] = daterangeUpdatedAt.value[0];
    queryParams.value.params["endUpdatedAt"] = formatEndDate(daterangeUpdatedAt.value[1]);
  }
  listSku(queryParams.value).then(response => {
    skuList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}
const formatEndDate = (dateStr) => {
  if (!dateStr) return dateStr;
  // 检查是否已经包含时间信息
  if (dateStr.includes(' ') || dateStr.includes('T')) {
    return dateStr;
  }
  // 只包含日期部分，添加23:59:59
  return `${dateStr} 23:59:59`;
};
function getSpuList() {
  listProductSpu(queryAllParams.value).then(response => {
    productSpuList.value = response.rows;
  });
}
/** 查询商品分类下拉树结构 */
function getCategoryTreeselect() {
  listProductCategory(queryAllParams.value).then(response => {
    // productCategoryOptions.value = [];
    const data = { id: null, name: '顶级节点', children: [] };
    data.children = proxy.handleTree(response.data, "id", "parentId");
    // productCategoryOptions.value.push(data);
  });
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 - 跳转到新增页面 */
function handleAdd() {
  router.push({ path: '/product/sku-edit/add' });
}

/** 修改按钮操作 - 跳转到编辑页面 */
function handleUpdate(row) {
  const id = row ? row.id : ids.value[0];
  router.push({ path: `/product/sku-edit/edit/${id}` });
}
/** 修改按钮操作 - 跳转到编辑页面 */
function handleDetail(row) {
  const id = row ? row.id : ids.value[0];
  router.push({ path: `/product/sku-edit/detail/${id}` });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row ? [row.id] : ids.value;
  proxy.$modal.confirm('是否确认删除商品SKU编号为"' + _ids + '"的数据项？').then(function () {
    return delSku(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/** 导出按钮操作 */
// function handleExport() {
//   proxy.download('product/sku/export', {
//     ...queryParams.value
//   }, `sku_${new Date().getTime()}.xlsx`)
// }

// 初始化加载列表数据
onMounted(() => {
  getList();
  getSpuList();
  getCategoryTreeselect();
})


</script>

<style scoped>
.image-cell {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 50px;
}

.product-image {
  border-radius: 4px;
  cursor: pointer;
  transition: transform 0.2s;
}

.product-image:hover {
  transform: scale(1.1);
}

.no-image {
  color: #999;
  font-size: 12px;
}
</style>
